﻿using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ZeroBug.EasyFlow.Core;

namespace EasyFlow
{
    /// <summary>
    /// StepInfoControl.xaml 的交互逻辑
    /// </summary>
    public partial class StepInfoControl : UserControl
    {
        public string GroupName
        {
            get { return (string)GetValue(GroupNameProperty); }
            set { SetValue(GroupNameProperty, value); }
        }
        public static readonly DependencyProperty GroupNameProperty =
            DependencyProperty.Register("GroupName", typeof(string), typeof(StepInfoControl), new PropertyMetadata(""));

        public ObservableCollection<StepInfo> Steps
        {
            get { return (ObservableCollection<StepInfo>)GetValue(StepsProperty); }
            set { SetValue(StepsProperty, value); }
        }

        public static readonly DependencyProperty StepsProperty =
            DependencyProperty.Register("Steps", typeof(ObservableCollection<StepInfo>), typeof(StepInfoControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

        public ICommand StepInfoDropCommand
        {
            get { return (ICommand)GetValue(StepInfoDropCommandProperty); }
            set { SetValue(StepInfoDropCommandProperty, value); }
        }

        public static readonly DependencyProperty StepInfoDropCommandProperty =
            DependencyProperty.Register("StepInfoDropCommand", typeof(ICommand), typeof(StepInfoControl), new PropertyMetadata(null));


        public StepInfoControl()
        {
            InitializeComponent();

            //GroupName = "hhh";
            //Steps = new ObservableCollection<StepInfo>();
            //Steps.Add(new StepInfo() { Group = StepGroup.Control, StepName = "bbb" });
        }

        private void ListBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed &&
                sender is FrameworkElement frameworkElement)
            {
                StepInfo item = (sender as ListBox).SelectedItem as StepInfo;
                ListBoxItem lbi = aaa.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;

                if (item == null)
                    return;
                DragDropEffects dragDropResult = DragDrop.DoDragDrop(frameworkElement, new DataObject(DataFormats.Serializable, item), DragDropEffects.Move);
                //WriteToPng(lbi, "");
                //if (dragDropResult == DragDropEffects.None)
                //{
                //    if (StepInfoDropCommand != null)
                //        StepInfoDropCommand.Execute(item);
                //}
            }
        }
        public void WriteToPng(UIElement element, string filename)
        {
            var rect = new Rect(element.RenderSize);
            var visual = new DrawingVisual();

            using (var dc = visual.RenderOpen())
            {
                dc.DrawRectangle(new VisualBrush(element), null, rect);
            }

            RenderTargetBitmap bitmap = new RenderTargetBitmap(
                (int)(rect.Width * 1.75), (int)(rect.Height * 1.75), 96 * 1.75, 96 * 1.75, PixelFormats.Default);
            bitmap.Render(visual);

            Bitmap bmp;
            using (var stream = new MemoryStream())
            {
                var e = new BmpBitmapEncoder();
                e.Frames.Add(BitmapFrame.Create(bitmap));
                e.Save(stream);
                bmp = new Bitmap(stream);
            }
            this.Cursor = BitmapCursor.CreateBmpCursor(bmp);

            //var encoder = new PngBitmapEncoder();
            //encoder.Frames.Add(BitmapFrame.Create(bitmap));

            //using (var file = File.OpenWrite(filename))
            //{
            //    encoder.Save(file);
            //}
        }

        private void ListBoxItem_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effects == DragDropEffects.Move)
            {
                e.UseDefaultCursors = false;
                WriteToPng(sender as FrameworkElement, "");

            }
            else
                e.UseDefaultCursors = true;
            e.Handled = true;
        }

        private void ListBox_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
            e.Handled = true;
        }
    }

    internal class BitmapCursor : SafeHandle
    {
        public override bool IsInvalid
        {
            get
            {
                return handle == (IntPtr)(-1);
            }
        }
        public static Cursor CreateBmpCursor(Bitmap cursorBitmap)
        {
            var c = new BitmapCursor(cursorBitmap);
            return CursorInteropHelper.Create(c);
        }
        
        protected BitmapCursor(Bitmap cursorBitmap)
        : base((IntPtr)(-1), true)
        {
            handle = cursorBitmap.GetHicon();
        }
        protected override bool ReleaseHandle()
        {
            bool result = DestroyIcon(handle);

            handle = (IntPtr)(-1);

            return result;
        }
        [DllImport("user32")]
        private static extern bool DestroyIcon(IntPtr hIcon);
    }
}
